/*

WARNING: DO NOT USE WITH MORE THAN THE FOLLOWING PARTS:
	MSP430G2452
	32768 CRYSTAL
	SW1/SW2 & 1M Ohm Pullup resistors.
	3.3V Regulator***

*** Do not use the 3.3V regulator AND the programming Vcc simultaneoulsy.
There is no protection for this.

This is designed to test the 32.768Khz crystal. It will generate a signal
at approximately 64Hz on all of P1 outputs.

*/

#include <msp430.h>
#include "main.h"

int index = 0;

void ButtonSelect()
{
	pwm_out[index] = 0x00;
	index++;
	if(index == 6)
	{
		index = 0;
	}
	pwm_out[index] = 0x02;
}
void ButtonEnter()
{
	pwm_out[index] = 0x00;
	index--;
	if(index == -1)
	{
		index = 5;
	}
	pwm_out[index] = 0x02;
}

int main()
{
	WDTCTL = WDTPW + WDTHOLD;

	DCOCTL = DCO0 | DCO1;
	BCSCTL1 = RSEL3 | RSEL2 | RSEL1 | RSEL0;	

	P2DIR = 0x3F;
	P2OUT = 0x00;

	P1DIR = ~(BUTTON_SEL | BUTTON_ENT);
	P1OUT = 0x00;

	TACTL = TASSEL_1 | MC_1;
	TACCTL0 = CCIE;
	CCR0 = EVENT_TIMER;
	TACCTL1 = CCIE;
	CCR1 = 1;

	while(1)
	{
		__bis_SR_register(LPM3_bits + GIE);
		CCR1 += 2;
		if(CCR1 > CCR0) CCR1 = 0x01;
	}

	return 0;
}

/*CCR0 Interrupt*/
#ifdef __GNUC__
__attribute__((interrupt(TIMER0_A0_VECTOR)))
#else
#pragma vector = TIMER0_A0_VECTOR
	__interrupt
#endif
void TIMER0_A0_ISR(void)
{
	unsigned char state;
	state = (P1IN ^ 0xFF) & (BUTTON_SEL | BUTTON_ENT); //Active Low

	//64Hz event timer
	switch(state)
	{
		case BUTTON_SEL | BUTTON_ENT:
			buzzkeeper.inputs.both_accum++;
			break;
		case BUTTON_SEL:
			buzzkeeper.inputs.select_accum++;
			break;
		case BUTTON_ENT:
			buzzkeeper.inputs.enter_accum++;
			break;
		default:
			if(buzzkeeper.inputs.both_accum > 16)
			{
			}
			else if(buzzkeeper.inputs.select_accum > 16)
			{
				ButtonSelect();
			}
			else if(buzzkeeper.inputs.enter_accum > 16)
			{
				ButtonEnter();
			}
			buzzkeeper.inputs.both_accum = 0;
			buzzkeeper.inputs.select_accum = 0;
			buzzkeeper.inputs.enter_accum = 0;
			break;
	}

}
